import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use((config) => {
  if (store.getters.token) {
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config
},
error => {
  return Promise.reject(error)
}
)

// response interceptor
service.interceptors.response.use((response) => {
  // 判断响应回来数据的类型
  if (response.data instanceof Blob) { return response.data }

  const { data, message, success } = response.data
  if (success) {
    return data
  } else {
    Message({ type: 'error', message })
    return Promise.reject(new Error(message))
  }
},
error => {
  if (error.response.status === 401) {
    Message({
      message: '登录过期了',
      type: 'error'
    })
    store.dispatch('user/logout')
    router.replace('/login')
  } else {
    Message({
      message: error.message,
      type: 'error'
    })
  }

  return Promise.reject(error)
}
)

export default service
